<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-button type="primary" @click="addTypeDialog">添加分类</el-button>

        <!-- 表格 -->
        <tree-table
          :data="cateList"
          :columns="columns"
          :selection-type="false"
          :expand-type="false"
          show-index
          index-text="#"
          border
        >
          <!-- 是否有效渲染 -->
          <template slot="isOK" slot-scope="scope">
            <i
              class="el-icon-success"
              v-if="scope.row.cat_deleted === false"
              style="color: lightgreen"
            ></i>
            <i class="el-icon-error" v-else style="color: red"></i>
          </template>
          <!-- 商品等级渲染 -->
          <template slot="level" slot-scope="scope">
            <el-tag v-if="scope.row.cat_level === 0" effect="dark">一级</el-tag>
            <el-tag
              v-else-if="scope.row.cat_level === 1"
              effect="dark"
              type="danger"
              >二级</el-tag
            >
            <el-tag v-else effect="dark" type="warning">三级</el-tag>
          </template>
          <!-- 操作模块渲染 -->
          <template slot="options" slot-scope="scope">
            <el-button icon="el-icon-edit" type="primary" size="mini"
              >操作</el-button
            >
            <el-button
              icon="el-icon-delete"
              type="danger"
              size="mini"
              @click="delateCate(scope.row)"
              >删除</el-button
            >
          </template>
        </tree-table>
      </el-row>
    </el-card>

    <!-- 分页功能 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="addTypeDialogVisible"
      width="50%"
      @close="dialogClose"
    >
      <!-- 添加分类的表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="ruleFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <!-- 父级分类列表级联选择 -->
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children'
            }"
            @change="cateParentChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addTypeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCateType">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 商品数据列表
      cateList: [],
      // 查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 总数据条数
      total: 0,
      // 为table指定列的定义
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          // 表示希望使用自定义组件的方式渲染
          type: 'template',
          // 自定义组件的作用域插槽
          template: 'isOK'
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'level'
        },
        {
          label: '操作',
          type: 'template',
          template: 'options'
        }
      ],
      // 对话框显示与隐藏数据
      addTypeDialogVisible: false,
      // 添加分类绑定数据
      addCateForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      // 分类数据规则
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'change' }
        ]
      },
      // 二级分类列表参数
      parentCateType: 2,
      // 父级分类列表
      parentCateList: [],
      // 选中的父级分类的数组ID
      selectedKeys: []
    }
  },
  methods: {
    // 获取商品数据
    async getCateData () {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('商品获取失败')
      } else {
        this.cateList = res.data.result
        this.total = res.data.total
      }
    },
    // 页面pagesize改变时触发
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateData()
    },
    handleCurrentChange (newNum) {
      this.queryInfo.pagenum = newNum
      this.getCateData()
    },
    // 获取父级分类列表数据
    async getParentCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: this.parentCateType
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.data)
      }
      this.parentCateList = res.data
      console.log(this.parentCateList)
    },
    // 单击打开添加分类对话框时间
    addTypeDialog () {
      this.getParentCateList()
      this.addTypeDialogVisible = true
    },
    // 父级分类发生变化触发函数
    parentCateListChanged () {
      this.cateParentChange()
    },
    cateParentChange () {
      if (this.selectedKeys.length > 0) {
        // 父级元素的id
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        // 当前数据的等级
        this.addCateForm.cat_level = this.selectedKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
      console.log(this.addCateForm)
    },
    // 监听添加分类对话框关闭
    dialogClose () {
      this.selectedKeys = []
      this.$refs.ruleFormRef.resetFields()
      this.addCateForm.cat_pid = ''
      this.addCateForm.cat_level = ''
    },
    // 点击对话框确定触发事件提交数据
    submitCateType () {
      // 确认选框填写正确
      this.$refs.ruleFormRef.validate(async valid => {
        if (!valid) return
        // 向服务器发送数据
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        if (res.meta.status !== 201) {
          console.log(res.meta.status)
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getCateData()
        this.addTypeDialogVisible = false
      })
    },
    // 删除商品分类
    async delateCate (cateRow) {
      const confirm = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      if (confirm === 'confirm') {
        console.log(cateRow.cat_name)
        const { data: res } = await this.$http.delete(
          'categories/' + cateRow.cat_id,
          cateRow.cat_name
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getCateData()
      }
    }
  },
  created () {
    this.getCateData()
  }
}
</script>
<style lang="less" scoped>
.el-card {
  margin-top: 20px;
}

.block {
  background-color: #fff;
  padding-top: 10px;
  text-align: center;
}
</style>
